package com.wocao.framework.security.service;

import com.wocao.commom.model.UserModel;
import com.wocao.system.entity.SysRoleDo;
import com.wocao.system.entity.SysUserDo;
import com.wocao.system.entity.SysUserRoleDo;
import com.wocao.system.service.SysRoleService;
import com.wocao.system.service.SysUserRoleService;
import com.wocao.system.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.util.List;

/**
 * 实现UserDetailService接口的方法
 *
 * @author sunhao
 * @date 2021/6/16
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        // 用户表查询用户信息
        SysUserDo sysUser = sysUserService.getSysUserByUserName(s);
        if (sysUser == null) {
            throw new UsernameNotFoundException("登录用户：" + s + "不存在");
        }
        // 角色表查询角色列表,放在字符串用逗号拼接
        List<SysUserRoleDo> sysUserRoleList = sysUserRoleService.listSysUserRolesByUserId(sysUser.getId());
        List<SysRoleDo> sysRoleDos = sysRoleService.listRolesByUserRoleList(sysUserRoleList);
        String rolsStr = getRolsStr(sysRoleDos);
        // 组装返回对象
        UserModel userModel = new UserModel();
        userModel.setUsername(sysUser.getUsername());
        userModel.setPassword(sysUser.getPassword());
        userModel.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList(rolsStr));
        return userModel;
    }

    /**
     * 功能描述: 组装角色字段<br>
     *
     * @param roleList 角色列表
     * @return java.lang.String
     * @author eggg 2021/6/16 9:53
     * @see [相关类/方法]（可选）
     * @since [产品/模块版本]（可选）
     */
    private String getRolsStr(List<SysRoleDo> roleList) {
        if (CollectionUtils.isEmpty(roleList)) {
            return null;
        }
        StringBuffer sb = new StringBuffer();
        for (SysRoleDo sysRoleDo : roleList) {
            sb.append(sysRoleDo.getRoleCode()).append(",");
        }
        String result = sb.toString();
        return result.substring(0, result.length() - 1);
    }

}
